package com.oxy.listener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.oxy.common.constant.AppConstant;
import com.oxy.common.util.FileUtil;
import com.oxy.util.Oxy;

public class AppInitListener implements ServletContextListener {
	public void contextDestroyed(ServletContextEvent evt) {
		doDestroy(evt);
	}

	public void contextInitialized(ServletContextEvent evt) {
		doInit(evt);
	}
	
	public void doInit(ServletContextEvent evt) {
		String sysPropFile = FileUtil.getSafePath(FileUtil.getClassPathAbsolute()+File.separator+AppConstant.SYS.SYSTEM_PROP_CFG_FILE);
		String realPathRoot = null;
		String urlPathRoot = null;
		// for tomcat initial
		if(evt != null && evt.getServletContext() != null) {
			ServletContext sc = evt.getServletContext();
			realPathRoot = FileUtil.getSafePath(sc.getRealPath("/"));
			urlPathRoot = sc.getContextPath();
		}
		// for local initial
		else {
			realPathRoot = FileUtil.getSafePath(FileUtil.getClassPathAbsolute()
					+File.separator+".."
					+File.separator+".."
					+File.separator+"WebContent");
			urlPathRoot = "/";
		}
		
		System.setProperty(AppConstant.SYS.PROPERTY_KEY.REALPATH_ROOT, realPathRoot);
		System.setProperty(AppConstant.SYS.PROPERTY_KEY.URLPATH_ROOT, urlPathRoot);
		
		Properties proptmp = new Properties();
		try {
			proptmp.load(new FileReader(new File(sysPropFile)));
			Enumeration<?> keys = proptmp.propertyNames();
			while(keys.hasMoreElements()) {
				String key = ((String)keys.nextElement()).trim();
				String val = proptmp.getProperty(key);
				if(val == null) {
					val = "";
				}
				else {
					val = val.trim();
				}
				System.setProperty(key,  val);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
		// init all system related resources
		Oxy.init();
		
		// 可以通过如SpringUtil类获取spring的bean
		// 初始化在CompInitListener中
	}
	
	public void doDestroy(ServletContextEvent evt) {
		// do nothing
	}
}
